package com.hx.utils;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WordBookmarkReplacer {

//    public static void main(String[] args) throws Exception {
//        String templatePath = "C:\\Users\\蓝色思维\\Desktop/测试模板.docx";
//        String outputPath = "C:\\Users\\蓝色思维\\Desktop/output.docx";
//        Map<String, String> bookmarkValues = new HashMap<>();
//        bookmarkValues.put("start","aaa");
//        bookmarkValues.put("end","bbb");
//
//
//    }

    public static void main(String[] args) throws IOException {
        String inputFilePath = "C:\\Users\\1\\Desktop/测试模板.docx";
        String outputFilePath = "C:\\Users\\1\\Desktop/output.docx";

        try (FileInputStream fis = new FileInputStream(inputFilePath);
             XWPFDocument doc = new XWPFDocument(fis);
             FileOutputStream fos = new FileOutputStream(outputFilePath)) {

            // 遍历文档中的所有段落
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                // 检查段落中是否有书签
                for (CTBookmark bookmark : paragraph.getCTP().getBookmarkStartList()) {
                    String bookmarkId = bookmark.getName();
                    BigInteger id = bookmark.getId();
                    // 检查书签ID是否是我们想要的那个
                    if ("start".equals(bookmarkId)) {
                        // 创建运行块并写入数据
                        XWPFRun run = paragraph.createRun();
                        run.setText("aaa");
                        // 可以继续添加更多的样式或数据
                    }
                }
            }

            // 保存修改后的文档
            doc.write(fos);
        }
    }
}
